﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ARchGL.Declaration.Platform.Service.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public class SystemHelper
    {
        private static string ip = string.Empty;
        private static string mac = string.Empty;

        /// <summary>  
        /// 获取当前网卡IP地址  
        /// </summary>  
        /// <returns></returns>  
        public static string GetLocalIpv4()
        {
            if (!string.IsNullOrWhiteSpace(ip)) return ip;

            var localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            var list = new List<string>();
            foreach (IPAddress ip in localIPs)
            {
                //根据AddressFamily判断是否为ipv4,如果是InterNetWork则为ipv6
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    list.Add(ip.ToString());
            }

            return ip = string.Join(",", list);//返回IPv4字符串
        }

        /// <summary>
        /// 获取第一块网卡 MAC 地址
        /// </summary>
        /// <returns></returns>
        public static string GetFirstMacAddress()
        {
            if (!string.IsNullOrWhiteSpace(mac)) return mac;

            var macAddresses = string.Empty;
            foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    macAddresses += nic.GetPhysicalAddress().ToString();
                    break;
                }
            }

            return mac = macAddresses;
        }

        /// <summary>
        /// 获取远程客户端的 IP 主机地址（无视代理，真实IP）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetUserHostAddress(HttpContext context)
        {
            var address = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(address))
            {
                if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    address = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            }
            if (string.IsNullOrEmpty(address))
            {
                address = HttpContext.Current.Request.UserHostAddress;
            }

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(address) && IsIPAddress(address))
            {
                return address;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 获取远程客户端的 IP 主机地址
        /// </summary>
        /// <returns></returns>
        public static string GetUserHostAddress()
        {
            var address = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(address))
            {
                address = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(address))
            {
                address = HttpContext.Current.Request.UserHostAddress;
            }
            if (!string.IsNullOrEmpty(address) && IsIPAddress(address))
            {
                return address;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}
